package com.loop.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 群聊服务器
 *
 * @author zhangxiaolu
 * @since 2023-09-16 20:22
 */
public class GroupChatServer {

    private int port; // 监听端口

    public GroupChatServer(int port) {
        this.port = port;
    }

    // 编写run方法，处理客户端的请求
    public void run() {
        // 创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();// 默认为8个

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 获取到pipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        // 向pipeline加入解码器
                        pipeline.addLast("decoder", new StringDecoder());
                        // 向pipeline加入编码器
                        pipeline.addLast("encoder", new StringEncoder());
                        // 加入自己的业务处理Handler
                        pipeline.addLast(new GroupChatServerHandler());
                    }
                });
        System.out.println("netty 服务器启动成功，端口是：" + port);
        // 绑定端口，同步等待成功
        ChannelFuture cf = null;
        try {
            cf = bootstrap.bind(port).sync();
            // 监听关闭
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭
//            cf.channel().close();
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new GroupChatServer(8081).run();
    }
}
